package com.group01.community.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Quarter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.group01.community.entity.ZyComplaintSuggest;
import com.group01.community.entity.vo.SysUserInfoVo;
import com.group01.community.entity.vo.ZyComplaintSuggestVo;
import com.group01.community.mapper.SysUserMapper;
import com.group01.community.service.ZyComplaintSuggestService;
import com.group01.community.utils.ResponseResult;
import com.group01.community.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 投诉建议  前端控制器
 * </p>
 *
 * @author guoyuan
 * @since 2025-05-01
 */
@Api(tags ="投诉建议" )
@RestController
@RequestMapping("/zyComplaintSuggest")
public class ZyComplaintSuggestController {


    @Autowired
    private ZyComplaintSuggestService zyComplaintSuggestService;

    @Resource
    private SysUserMapper sysUserMapper;

    @ApiOperation("查询所有投诉建议 季度")
    @GetMapping("/quarter")
    public ResponseResult<ArrayList<Integer>> getZyComplaintSuggests() {

        List<ZyComplaintSuggest> list = zyComplaintSuggestService.list();
        int q1 = 0; // 第一季度
        int q2 = 0; // 第二季度
        int q3 = 0; // 第三季度
        int q4 = 0; // 第四季度
        for (ZyComplaintSuggest su : list) {
            LocalDateTime createTime = su.getCreateTime();
            ZonedDateTime zonedDateTime = createTime.atZone(ZoneId.systemDefault());
            Date datefrom = Date.from(zonedDateTime.toInstant());
            Quarter quarter = DateUtil.quarterEnum(datefrom);
            switch (quarter) {
                case Q1: q1 += 1; break;
                case Q2: q2 += 1; break;
                case Q3: q3 += 1; break;
                case Q4: q4 += 1; break;
                default: break;
            }
        }
        return ResponseResult.ok(CollUtil.newArrayList(q1, q2, q3, q4));
    }

    @ApiOperation("根据状态查询所有投诉建议")
    @GetMapping
    public ResponseResult<IPage<ZyComplaintSuggestVo>> getZyComplaintSuggests(Long current, Long pageSize, ZyComplaintSuggest zyComplaintSuggest) {
        IPage<ZyComplaintSuggestVo> data = zyComplaintSuggestService.getZyComplaintSuggestPage(current, pageSize, zyComplaintSuggest);
        return ResponseResult.ok(data);
    }

    //表格导出接口
    @ApiOperation("投诉建议导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        //查询所有用户

//        List<ZyVisitor> all = zyVisitorService.selectZyVisitor();
        List<ZyComplaintSuggest> all = zyComplaintSuggestService.list();


        //在内存操作，写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        try {
            //自定义标题别名
            writer.addHeaderAlias("communityId", "id");
            writer.addHeaderAlias("complaintSuggestId", "小区id");
            writer.addHeaderAlias("complaintSuggestType", "类型");
            writer.addHeaderAlias("visitorPhoneNumber", "创建者手机号");
            writer.addHeaderAlias("complaintSuggestContent", "内容");
            writer.addHeaderAlias("createBy", "创建名称");
            writer.addHeaderAlias("createTime", "创建时间");
            writer.addHeaderAlias("ownerNickname", "创建时间");


            //默认配置
            writer.write(all, true);
            //设置content—type
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

            //设置标题
            String fileName = URLEncoder.encode("投诉建议信息表", "UTF-8");
            //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();

            //将Writer刷新到OutPut
            writer.flush(outputStream, true);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

//    - 添加投诉建议
//    - 个人投诉建议信息列表
//    - 投诉建议反馈查询

    @ApiOperation("添加投诉建议")
    @PostMapping
    public ResponseResult<String> add(@RequestBody ZyComplaintSuggest zyComplaintSuggest) {
        zyComplaintSuggest.setComplaintSuggestId(UUIDUtils.getId());

        String userName = SecurityContextHolder.getContext().getAuthentication().getName();
        zyComplaintSuggest.setCreateTime(LocalDateTime.now());
        zyComplaintSuggest.setCreateBy(userName);

        zyComplaintSuggest.setUpdateBy(userName);
        zyComplaintSuggest.setUpdateTime(LocalDateTime.now());


        SysUserInfoVo userInfoByUserName = sysUserMapper.getUserInfoByUserName(userName);
        zyComplaintSuggest.setUserId(userInfoByUserName.getUserId());

        zyComplaintSuggestService.save(zyComplaintSuggest);
        return ResponseResult.ok("ok");
    }


    @ApiOperation(value = "人投诉建议信息列表", notes = "根据userid查询报修建议")
    @GetMapping("/{userId}")
    public ResponseResult<List<ZyComplaintSuggest>> getComplaintSuggest(@PathVariable String userId) {
        List<ZyComplaintSuggest> list = zyComplaintSuggestService.list(new QueryWrapper<ZyComplaintSuggest>().eq("user_id",userId));
        return ResponseResult.ok(list);
    }

    @ApiOperation(value = "投诉建议反馈查询",notes = "反馈就是写备注")
    @PutMapping("/update")
    public ResponseResult<String> updateSuggest(@RequestBody ZyComplaintSuggest zyComplaintSuggest) {
        zyComplaintSuggestService.updateById(zyComplaintSuggest);
        return ResponseResult.ok("ok");
    }


    @ApiOperation(value = "删除投诉或建议",notes = "根据投诉建议id 删除")
    @DeleteMapping("/{complaintSuggestId}")
    public ResponseResult<String> updateSuggest(@PathVariable String complaintSuggestId) {
        zyComplaintSuggestService.removeById(complaintSuggestId);
        return ResponseResult.ok("ok");
    }




}

